<?php
/**
 * Poup to Create a new Patient
 * Display a form with patient required fields.
 *
 * @author Xavier VILAIN
 * @package Nawa\MedicalStudy\MedicalCenter\Patient
 * @license
 *
 */

use Fox\Core\Errors;
use Fox\Generator;
use Nawa\MedicalStudy\MedicalCenter\Patient;
use Fox\Popup;
use Fox\Html\Screen;

$xview = Xview::instance();
$msid = $xview->val('msid');
$mcid = $xview->val('mcid');
$screen = new Screen('sAddPatient','add',null,true,
Generator::ajaxReload('MC_patients'));
$block = $xview->component('medicalstudies','patientBlock');
$screen->add($block);
if($screen->submitted())
{
	$fields = $screen->get();
	if(!$screen->errors()) {
		// Compare Selection Date VS Inclusion Date
		if(!empty($fields['selection_date']) && !empty($fields['inclusion_date'])) {
			if($fields['selection_date'] > $fields['inclusion_date']) {
				Fox\Message::Error(Msg(Nawa\Messages::BUNDLE,Nawa\Messages::ERR_X_LOWER_THAN_Y,
					$block->item('selection_date')->label(),
					$block->item('inclusion_date')->label()));
			}
		}
	}
	
	if(!$screen->errors())
	{
		try {
			$patient = new Patient();
			$fields['msid'] = $msid;
			$fields['mcid'] = $mcid;
			$patient->setFields($fields);
			$patient->create();
			Fox\Message::Success(Msg(Nawa\Messages::BUNDLE,
									Nawa\Messages::PATIENT_CREATION_SUCESS,
									$fields['reference']));
			
		}
		catch (Fox\Object\Exception\Save $e)
		{
			Fox\Message::Error($e);
		}
	}
	echo $xview->messages(true,true);
	exit;
}
$popup = new Popup('pAddPatient',Msg(Nawa\Messages::BUNDLE,Nawa\Messages::PATIENT_ADD_TITLE),$screen);
if($screen->errors())
{
	echo Xview::instance()->messages();
}
else
{
	echo $popup->display();
}